package cn.lili.modules.goods.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.goods.client.GoodsSkuClient;
import cn.lili.modules.goods.entity.dos.Goods;
import cn.lili.modules.goods.entity.dos.GoodsGallery;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.dto.GoodsSkuDTO;
import cn.lili.modules.goods.entity.dto.StoreShareDTO;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.vos.GoodsSkuVO;
import cn.lili.modules.goods.entity.vos.SpecValueVO;
import cn.lili.modules.goods.mapper.GoodsSkuMapper;
import cn.lili.modules.goods.service.GoodsGalleryService;
import cn.lili.modules.goods.service.GoodsSkuService;
import cn.lili.modules.promotion.client.PromotionGoodsClient;
import cn.lili.modules.promotion.client.ReturnActivityGoodsClient;
import cn.lili.modules.promotion.entity.dos.PromotionGoods;
import cn.lili.modules.promotion.entity.dos.ReturnActivityGoods;
import cn.lili.modules.promotion.entity.dto.search.PromotionGoodsSearchParams;
import cn.lili.modules.promotion.entity.enums.PromotionsStatusEnum;
import cn.lili.mybatis.model.BaseStandardEntity;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.mybatis.util.SceneHelp;
import cn.lili.routing.GoodsRoutingKey;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品sku业务层实现
 *
 * @author pikachu
 * @since 2020-02-23 15:18:56
 */
@Service
@RequiredArgsConstructor
public class GoodsSkuServiceImpl extends ServiceImpl<GoodsSkuMapper, GoodsSku> implements GoodsSkuService {

    /**
     * 缓存
     */
    private final Cache cache;


    private final ApplicationEventPublisher applicationEventPublisher;

    private final AmqpExchangeProperties amqpExchangeProperties;

    private final GoodsGalleryService goodsGalleryService;

    private final PromotionGoodsClient promotionGoodsClient;

    private final ReturnActivityGoodsClient returnActivityGoodsClient;

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateBatch(List<GoodsSku> skuList) {
        if (!skuList.isEmpty()) {
            LambdaQueryWrapper<GoodsSku> unnecessarySkuIdsQuery = new LambdaQueryWrapper<>();
            unnecessarySkuIdsQuery.eq(GoodsSku::getGoodsId, skuList.get(0).getGoodsId());
            unnecessarySkuIdsQuery.notIn(GoodsSku::getId,
                    skuList.stream().map(BaseStandardEntity::getId).collect(Collectors.toList()));
            List<GoodsSku> unnecessarySkuList = this.list(unnecessarySkuIdsQuery);
            if (!unnecessarySkuList.isEmpty()) {
                this.removeBatchByIds(unnecessarySkuList.stream().map(BaseStandardEntity::getId).collect(Collectors.toList()));
            }

            this.saveOrUpdateBatch(skuList);
            //删除缓存
            for (GoodsSku goodsSku : skuList) {
                cache.remove(GoodsSkuService.getCacheKeys(goodsSku.getId()));
            }
        }
    }

    /**
     * 更新商品sku
     *
     * @param goodsSku sku信息
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void update(GoodsSku goodsSku) {
        this.updateById(goodsSku);
        cache.remove(GoodsSkuService.getCacheKeys(goodsSku.getId()));
        cache.put(GoodsSkuService.getCacheKeys(goodsSku.getId()), goodsSku);
    }

    @Override
    public void delete(List<String> skuIdList) {
        LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(GoodsSku::getMarketEnable, GoodsMarketEnum.DOWN.name());
        updateWrapper.set(GoodsSku::getDeleteFlag, true);
        updateWrapper.in(GoodsSku::getId, skuIdList);
        this.baseMapper.update(null,updateWrapper);
        skuIdList.forEach(skuId->cache.remove(GoodsSkuService.getCacheKeys(skuId)));
    }


    /*
     * 清除sku缓存
     *
     * @param skuId skuID
     */
    @Override
    public void clearCache(String skuId) {
        cache.remove(GoodsSkuService.getCacheKeys(skuId));
    }

    @Override
    public GoodsSku getGoodsSkuByIdFromCache(String id) {
        //获取缓存中的sku
        GoodsSku goodsSku = (GoodsSku) cache.get(GoodsSkuService.getCacheKeys(id));
        //如果缓存中没有信息，则查询数据库，然后写入缓存
        if (goodsSku == null || StringUtils.isEmpty(goodsSku.getThumbnail()) || !goodsSku.getThumbnail().startsWith("http") || !goodsSku.getThumbnail().startsWith("https")) {
            goodsSku = this.getById(id);
            if (goodsSku == null) {
                return null;
            }
            cache.put(GoodsSkuService.getCacheKeys(id), goodsSku);
        }

        //获取商品库存
        Integer integer = (Integer) cache.get(GoodsSkuClient.getStockCacheKey(goodsSku));

        //库存不为空,库存与缓存中不一致
        if (integer != null && !goodsSku.getQuantity().equals(integer)) {
            //写入最新的库存信息
            goodsSku.setQuantity(integer);
            cache.put(GoodsSkuService.getCacheKeys(goodsSku.getId()), goodsSku);
        }
        return goodsSku;
    }

    /**
     * 更新商品sku状态
     *
     * @param goods 商品信息(Id,MarketEnable/AuthFlag)
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoodsSkuStatus(Goods goods) {
        LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CharSequenceUtil.isNotEmpty(goods.getId()), GoodsSku::getGoodsId, goods.getId());
        updateWrapper.eq(CharSequenceUtil.isNotEmpty(goods.getStoreId()), GoodsSku::getStoreId, goods.getStoreId());
        updateWrapper.set(GoodsSku::getMarketEnable, goods.getMarketEnable());
        updateWrapper.set(GoodsSku::getAuthFlag, goods.getAuthFlag());
        updateWrapper.set(GoodsSku::getDeleteFlag, true);
        boolean update = this.update(updateWrapper);
        if (Boolean.TRUE.equals(update)) {
            List<GoodsSku> goodsSkus = this.getGoodsSkuListByGoodsId(Collections.singletonList(goods.getId()));
            for (GoodsSku sku : goodsSkus) {
                cache.remove(GoodsSkuService.getCacheKeys(sku.getId()));
                cache.put(GoodsSkuService.getCacheKeys(sku.getId()), sku);
            }
        }
    }

    /**
     * 更新商品sku状态根据店铺id
     *
     * @param storeId      店铺id
     * @param marketEnable 市场启用状态
     * @param authFlag     审核状态
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateGoodsSkuStatusByStoreId(String storeId, String marketEnable, String authFlag) {
        LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoodsSku::getStoreId, storeId);
        updateWrapper.set(CharSequenceUtil.isNotEmpty(marketEnable), GoodsSku::getMarketEnable, marketEnable);
        updateWrapper.set(CharSequenceUtil.isNotEmpty(authFlag), GoodsSku::getAuthFlag, authFlag);
        boolean update = this.update(updateWrapper);
        if (Boolean.TRUE.equals(update)) {
            if (GoodsMarketEnum.UPPER.name().equals(marketEnable)) {
                applicationEventPublisher.publishEvent(
                        TransactionCommitSendMQEvent.builder()
                                .source("生成店铺商品")
                                .exchange(amqpExchangeProperties.getGoods())
                                .routingKey(GoodsRoutingKey.GENERATOR_STORE_GOODS_INDEX)
                                .message(storeId).build()
                );
            } else if (GoodsMarketEnum.DOWN.name().equals(marketEnable)) {
                cache.vagueDel(CachePrefix.GOODS_SKU.getPrefix());
                applicationEventPublisher.publishEvent(
                        TransactionCommitSendMQEvent.builder()
                                .source("删除店铺商品")
                                .exchange(amqpExchangeProperties.getGoods())
                                .routingKey(GoodsRoutingKey.STORE_GOODS_DELETE)
                                .message(storeId).build()
                );
            }
        }
    }

    @Override
    public List<GoodsSku> getGoodsSkuByIdFromCache(List<String> ids) {
        List<String> keys = new ArrayList<>();
        for (String id : ids) {
            keys.add(GoodsSkuService.getCacheKeys(id));
        }
        List<GoodsSku> list = cache.multiGet(keys);
        if (list == null || list.isEmpty()) {
            list = new ArrayList<>();
            List<GoodsSku> goodsSkus = listByIds(ids);
            for (GoodsSku skus : goodsSkus) {
                cache.put(GoodsSkuService.getCacheKeys(skus.getId()), skus);
                list.add(skus);
            }
        }
        return list;
    }

    @Override
    public List<GoodsSkuVO> getGoodsListByGoodsId(GoodsSearchParams searchParams) {
        List<GoodsSku> list = this.list(searchParams.queryWrapper());
        return this.getGoodsSkuVOList(list);
    }


    @Override
    public List<GoodsSku> getGoodsSkuListByGoodsId(String goodsId) {
        return this.list(new LambdaQueryWrapper<GoodsSku>().eq(GoodsSku::getGoodsId, goodsId));
    }

    /**
     * 获取goodsId下所有的goodsSku
     *
     * @param goodsIds 商品id
     * @return goodsSku列表
     */
    @Override
    public List<GoodsSku> getGoodsSkuListByGoodsId(List<String> goodsIds) {
        return this.list(new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getGoodsId, goodsIds));
    }

    @Override
    public List<String> getGoodsSkuIdListByGoodsId(GoodsSearchParams searchParams) {
        return this.baseMapper.getGoodsSkuIdByGoodsIdList(searchParams.queryWrapperGoodsSkuByCustomSql());
    }

    @Override
    public List<GoodsSkuVO> getGoodsSkuVOList(List<GoodsSku> list) {
        List<GoodsSkuVO> goodsSkuVOS = new ArrayList<>();

        if(list!=null&&!list.isEmpty()){
            List<GoodsGallery> goodsGalleriesS = goodsGalleryService.list(new LambdaQueryWrapper<GoodsGallery>().in(GoodsGallery::getGoodsId, list.stream().map(GoodsSku::getGoodsId).toList()));
            for (GoodsSku goodsSku : list) {
                GoodsSkuVO goodsSkuVO = this.getGoodsSkuVO(goodsSku, goodsGalleriesS);
                goodsSkuVOS.add(goodsSkuVO);
            }
        }
        return goodsSkuVOS;
    }

    @Override
    public GoodsSkuVO getGoodsSkuVO(GoodsSku goodsSku, List<GoodsGallery> goodsGalleriesS) {
        //初始化商品
        GoodsSkuVO goodsSkuVO = new GoodsSkuVO(goodsSku);
        //获取sku信息
        JSONObject jsonObject = JSONUtil.parseObj(goodsSku.getSpecs());
        //用于接受sku信息
        List<SpecValueVO> specValueVOS = new ArrayList<>();

        //循环提交的sku表单
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            SpecValueVO specValueVO = new SpecValueVO();
            if ("images".equals(entry.getKey())) {
                specValueVO.setSpecName(entry.getKey());
                if (entry.getValue().toString().contains("url")) {
                    List<SpecValueVO.SpecImages> specImages = JSONUtil.toList(JSONUtil.parseArray(entry.getValue()),
                            SpecValueVO.SpecImages.class);
                    specValueVO.setSpecImage(specImages);
                }
            } else {
                specValueVO.setSpecName(entry.getKey());
                specValueVO.setSpecValue(entry.getValue().toString());
            }
            specValueVOS.add(specValueVO);
        }

        if (CollectionUtil.isNotEmpty(goodsGalleriesS)) {
            Map<String, List<GoodsGallery>> goodsGalleriesMap = goodsGalleriesS.stream().filter(f -> StringUtils.isNotEmpty(f.getGoodsId())).collect(Collectors.groupingBy(GoodsGallery::getGoodsId));
            List<GoodsGallery> goodsGallerieList = goodsGalleriesMap.get(goodsSku.getGoodsId());
            if (CollectionUtil.isNotEmpty(goodsGallerieList)) {
                goodsSkuVO.setGoodsGalleryList(goodsGallerieList.stream().map(GoodsGallery::getThumbnail).collect(Collectors.toList()));
            }
        }
        goodsSkuVO.setSpecList(specValueVOS);
        return goodsSkuVO;
    }

    @Override
    public Page<GoodsSku> getGoodsSkuByPage(GoodsSearchParams searchParams) {
        QueryWrapper<GoodsSku> queryWrapper = searchParams.queryWrapper();

        // 全返商品查询，过滤促销活动商品
        if (null != searchParams.getSceneType() && 0 == searchParams.getSceneType()) {
            PromotionGoodsSearchParams params = new PromotionGoodsSearchParams();
            params.setPromotionStatus(PromotionsStatusEnum.START.name() + "," + PromotionsStatusEnum.NEW.name());
            params.setStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
            List<PromotionGoods> promotionGoodsList = promotionGoodsClient.listFindAll(params);
            if (!promotionGoodsList.isEmpty()) {
                List<String> goodsList = promotionGoodsList.stream().map(PromotionGoods::getGoodsId).toList();
                if (!goodsList.isEmpty()) {
                    queryWrapper.notIn("goods_id", goodsList);
                }
            }
        }else if (null != searchParams.getSceneType() && 1 == searchParams.getSceneType()) {
            // 分销商品 只能选择绿色积分大于0的商品
            queryWrapper.gt("green_score", 0);
        }else if (null != searchParams.getSceneType() && 2 == searchParams.getSceneType()) {
            // 红包和积分商品过滤供应商商品
            queryWrapper.ne("scene", SceneEnums.SUPPLIER.name());
        }else {
            // 过滤全返商品
            List<ReturnActivityGoods> returnActivityGoodsList = returnActivityGoodsClient.getListByStoreId(Objects.requireNonNull(UserContext.getCurrentUser()).getExtendId());
            if (!returnActivityGoodsList.isEmpty()) {
                List<String> goodsList = returnActivityGoodsList.stream().map(ReturnActivityGoods::getGoodsId).toList();
                queryWrapper.notIn("goods_id", goodsList);
            }
            /*if (StringUtils.isEmpty(searchParams.getGoodsId())) {
                queryWrapper.and(q-> q.eq("is_vip_goods",Boolean.FALSE).or().isNull("is_vip_goods"));
            }*/
        }
        SceneHelp.queryHandler(queryWrapper, true);
        Page<GoodsSku> page = this.page(PageUtil.initPage(searchParams), queryWrapper);
        if (page.getRecords().isEmpty() || CharSequenceUtil.isEmpty(page.getRecords().get(0).getSupplierSkuId())) {
            return page;
        } else {
            //如果供应商商品则获取供应商商品库存展示
            page.getRecords().forEach(item -> {
                item.setBackGreenPoint(item.generateBackGreenPoint(item.getGreenScore()));
                if (CharSequenceUtil.isNotEmpty(item.getSupplierSkuId())) {
                    item.setQuantity(getStock(item.getSupplierSkuId()));
                }
            });
        }
        return page;
    }

    @Override
    public Page<GoodsSkuDTO> getGoodsSkuDTOByPage(Page<GoodsSkuDTO> page, Wrapper<GoodsSkuDTO> queryWrapper) {
        return this.baseMapper.queryByParams(page, queryWrapper);
    }

    /**
     * 列表查询商品sku信息
     *
     * @param searchParams 查询参数
     * @return 商品sku信息
     */
    @Override
    public List<GoodsSku> getGoodsSkuByList(GoodsSearchParams searchParams) {
        return this.list(searchParams.queryWrapper());
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateStocks(List<GoodsSku> goodsSkuList) {
        for (GoodsSku goodsSku : goodsSkuList) {
            this.updateStock(goodsSku.getId(), goodsSku.getQuantity());
        }
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void updateStock(String skuId, Integer quantity) {
        GoodsSku goodsSku = getGoodsSkuByIdFromCache(skuId);
        if (goodsSku != null) {
            goodsSku.setQuantity(quantity);
            boolean update =
                    this.update(new LambdaUpdateWrapper<GoodsSku>().eq(GoodsSku::getId, skuId).set(GoodsSku::getQuantity, quantity));
            if (update) {
                cache.remove(CachePrefix.GOODS.getPrefix() + goodsSku.getGoodsId());
            }
            cache.put(GoodsSkuService.getCacheKeys(skuId), goodsSku);
            cache.put(GoodsSkuClient.getStockCacheKey(goodsSku), quantity);
        }
    }

    @Override
    @Transactional
    public void updateStock(List<GoodsSku> goodsSkus) {
        for (GoodsSku sku : goodsSkus) {
            this.update(new LambdaUpdateWrapper<GoodsSku>().eq(GoodsSku::getId, sku.getId()).set(GoodsSku::getQuantity, sku.getQuantity()));
            cache.put(GoodsSkuService.getCacheKeys(sku.getId()), sku);
            cache.put(GoodsSkuClient.getStockCacheKey(sku), sku.getQuantity());
        }
    }

    @Override
    public Integer getStock(String skuId) {
        String skuKey = CachePrefix.SKU_STOCK.getPrefix() + skuId;

        Integer stock = (Integer) cache.get(skuKey);
        if (stock != null) {
            return stock;
        } else {
            GoodsSku goodsSku = getGoodsSkuByIdFromCache(skuId);
            if (goodsSku == null) {
                return 0;
            }
            if (Boolean.TRUE.equals(goodsSku.getIsProxyGoods())) {
                skuKey = CachePrefix.SKU_STOCK.getPrefix() + goodsSku.getSupplierSkuId();
                goodsSku = getGoodsSkuByIdFromCache(goodsSku.getSupplierSkuId());
            }
            cache.put(skuKey, goodsSku.getQuantity());
            return goodsSku.getQuantity();
        }
    }

    @Override
    public Integer getGoodsStock(String goodsId) {
        List<String> skuIds = this.getSkuIdsByGoodsId(goodsId);

        Integer stock = 0;

        for (String skuId : skuIds) {
            stock += this.getStock(skuId);
        }
        return stock;

    }

    @Override
    public void updateGoodsSkuGrade(String goodsId, double grade, int commentNum) {
        LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoodsSku::getGoodsId, goodsId);
        updateWrapper.set(GoodsSku::getGrade, grade);
        updateWrapper.set(GoodsSku::getCommentNum, commentNum);
        this.update(updateWrapper);
    }

    /**
     * 根据商品id获取全部skuId的集合
     *
     * @param goodsId goodsId
     * @return 全部skuId的集合
     */
    @Override
    public List<String> getSkuIdsByGoodsId(String goodsId) {
        return this.baseMapper.getGoodsSkuIdByGoodsId(goodsId);
    }

    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public boolean deleteAndInsertGoodsSkus(List<GoodsSku> goodsSkus) {
        int count = 0;
        for (GoodsSku skus : goodsSkus) {
            if (CharSequenceUtil.isEmpty(skus.getId())) {
                skus.setId(SnowFlake.getIdStr());
            }
            count = this.baseMapper.replaceGoodsSku(skus);
        }
        return count > 0;
    }

    @Override
    public Long countSkuNum(String storeId) {
        LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper
                .eq(GoodsSku::getStoreId, storeId)
                .eq(GoodsSku::getDeleteFlag, Boolean.FALSE)
                .eq(GoodsSku::getAuthFlag, GoodsAuthEnum.PASS.name())
                .eq(GoodsSku::getMarketEnable, GoodsMarketEnum.UPPER.name());
        return this.count(queryWrapper);
    }

    @Override
    public void updateImages(List<GoodsSku> skuList) {
        for (GoodsSku goodsSku : skuList) {
            LambdaUpdateWrapper<GoodsSku> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(GoodsSku::getSpecs,goodsSku.getSpecs());
            updateWrapper.set(GoodsSku::getSmall,goodsSku.getSmall());
            updateWrapper.set(GoodsSku::getBig,goodsSku.getBig());
            updateWrapper.set(GoodsSku::getThumbnail,goodsSku.getThumbnail());
            updateWrapper.eq(GoodsSku::getId,goodsSku.getId());
            this.baseMapper.update(null,updateWrapper);

        }
    }

    /**
     *  如果已存在该分类替换掉，然后在批量追加。 普通商品
     *
     * @param ids 商品id
     * @param categoryPathSon 分类id
     * @param categoryPathSonName 分类名
     */
    @Override
    public void updateCategoryById(String ids, String categoryPathSon, String categoryPathSonName) {
        this.baseMapper.replaceCategoryById(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
        this.baseMapper.updateCategoryById(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
    }

    /**
     *  如果已存在该分类替换掉，然后在批量追加。 代理商品
     *
     * @param ids 商品id
     * @param categoryPathSon 分类id
     * @param categoryPathSonName 分类名
     */
    @Override
    public void updateCategoryByIdOrSupplierId(String ids, String categoryPathSon, String categoryPathSonName) {
        this.baseMapper.replaceCategoryByIdOrSupplierId(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
        this.baseMapper.updateCategoryByIdOrSupplierId(Arrays.stream(ids.split(",")).collect(Collectors.toList()), "'"+categoryPathSon+"'", "'"+categoryPathSonName+"'");
    }

    /**
     * 根据goodsId集合重置sku缓存
     * @param goodsIds
     */
    @Override
    public void updateGoodsSkuCache (List<String> goodsIds) {
        List<GoodsSku> goodsSkus = getGoodsSkuListByGoodsId(goodsIds);
        if (!goodsSkus.isEmpty()) {
            for (GoodsSku sku : goodsSkus) {
                // 缓存替换为新的sku信息
                if (sku.getAuthFlag().equals(GoodsAuthEnum.PASS.name()) && GoodsMarketEnum.UPPER.name().equals(sku.getMarketEnable())) {
                    cache.remove(CachePrefix.GOODS_SKU.getPrefix() + sku.getId());
                    cache.put(CachePrefix.GOODS_SKU.getPrefix() + sku.getId(), sku);
                }else{
                    //否则，清除缓存中的sku数据
                    cache.remove(CachePrefix.GOODS_SKU.getPrefix() + sku.getId());
                }
            }
        }
    }

    /**
     * 根据店铺获取店铺的套餐商品规格
     * @param storeIds
     * @return
     */
    @Override
    public List<GoodsSku> getGoodsSkuByStoreIds(List<String> storeIds) {
        LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(GoodsSku::getStoreId, storeIds);
        queryWrapper.eq(GoodsSku::getAuthFlag, GoodsAuthEnum.PASS.name());
        queryWrapper.eq(GoodsSku::getMarketEnable, GoodsMarketEnum.UPPER.name());
        queryWrapper.eq(GoodsSku::getIsMeal, 1);
        queryWrapper.eq(GoodsSku::getIsDefaultMeal, 1);
        return this.list(queryWrapper);
    }

    @Override
    public GoodsSku getBySkuName(String goodsId, String skuName) {
        LambdaQueryWrapper<GoodsSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsSku::getGoodsId, goodsId);
        queryWrapper.eq(GoodsSku::getSimpleSpecs, skuName);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public GoodsSku getGoodsSkuById(String skuId) {
        return baseMapper.getGoodsSkuById(skuId);
    }

    /**
     * PLUS会员礼包-获取店主分享列表商品
     * @param dto
     * @return
     */
    @Override
    public Page<StoreShareDTO> selectStoreShareList(StoreShareDTO dto) {
        dto.setNotConvert(true);
        if (StrUtil.isNotEmpty(dto.getSort()) && dto.getSort().equals("releaseTime")) {
            dto.setSort(null);
            dto.setOrder(null);
        }
        if (StrUtil.isNotEmpty(dto.getCategoryIds())) {
            dto.setCategoryIdList(Arrays.asList(dto.getCategoryIds().split(",")));
        }
        Page<StoreShareDTO> page = baseMapper.selectStoreShareList(new Page(dto.getPageNumber(), dto.getPageSize()), dto);

        return page;
    }
}
